package com.i72.basic.init;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import com.i72.basic.tools.BeanHelper;
import com.i72.basic.consts.Consts;
import com.i72.basic.context.GlobalContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 日志初始化
 */
@Component
@Slf4j
public class LogInit implements EnvironmentAware, Ordered {


    private final static String APP_LOGBACK_CONFIG_PATH="logback.xml";



    @Override
    public void setEnvironment(Environment environment) {

        initConfig(environment);


        ClassPathResource condition = new ClassPathResource(APP_LOGBACK_CONFIG_PATH);

        if(condition==null || !condition.exists()) {

            LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            JoranConfigurator joranConfigurator = new JoranConfigurator();
            joranConfigurator.setContext(context);
            context.reset();

            ClassPathResource classPathResource = new ClassPathResource(Consts.LOGBACK_DEFAULT_CONFIG_PATH);

            if (classPathResource.exists()) {
                try {
                    joranConfigurator.doConfigure(classPathResource.getFile());
                } catch (Exception e) {


                }
            }
        }




    }


    private String getPackagesInfo(){
        String packageName = Consts.SANC_BASE_PACKAGE+"."+GlobalContext.getAPPName();

        List<Class> classList = BeanHelper.scanPackage(Service.class,packageName);

        if(classList!=null && classList.size()>0){
            return packageName;
        }

        return "";
    }

    private void initConfig(Environment environment){
        GlobalContext.setAPPName(environment.getProperty(Consts.GOVERNANCE_SERVER_SERVICENAME));
        GlobalContext.setSubscribelist(environment.getProperty(Consts.GOVERNANCE_SERVER_SUBSCRIBE));

        String packageName = getPackagesInfo();

        /*
        if(StringUtils.isEmpty(packageName)){
            log.error("应用名与包名不一致或未实现任何服务");
            return;
        }*/
        GlobalContext.setAPPPackage(packageName);
    }


    @Override
    public int getOrder() {
        //延后是为了等待服务模块，加载完远程配置
        return Ordered.HIGHEST_PRECEDENCE+1;
    }
}
